package synapsolution;

import java.util.ArrayList;
import java.util.Random;

public class Neuron extends ArrayList<Synapse> {

    double value;
    boolean activated = false;
    static final double threshold = 3, mutationRate = .2;
    final ThreadLocal<Random> rng = new ThreadLocal<Random>();

    public Neuron(Layer outputLayer) {
        for (Neuron n : outputLayer) this.add(new Synapse(n));
        rng.set(new Random());
    }

    public Neuron() {
        rng.set(new Random());
    }

    public void activate(double amount) {
        value += amount;
    }

    public void checkFire() {
        if (value >= threshold) {
            activated = true;
            fire();
            value = 0;
        }
    }

    public void fire() {
        for (Synapse v : this) v.send();
    }

    public void combine(Neuron a, Neuron b) {
        for (int i = 0; i < this.size(); i++) this.get(i).combine(a.get(i), b.get(i));
        if (rng.get().nextDouble() < mutationRate) mutate();
    }

    public void mutate() {
        for (int i = 0; i < Population.randomSmall(this.size()) + 1; i++) this.get(rng.get().nextInt(this.size())).mutate();
    }

    @Override
    public String toString() {
        String out = "[";
        for (Synapse s : this) out += s + " ";
        return out + "]";
    }
}
